<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-content">
        <h1 class="system-title">
          钓鱼论坛后台管理系统
        </h1>
        <div class="login-box">
          <h2 class="login-heading">
            管理员登录
          </h2>
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            @keyup.enter.native="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名"
                prefix-icon="el-icon-user"
                size="medium"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                prefix-icon="el-icon-lock"
                show-password
                size="medium"
              />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input
                    v-model="loginForm.captcha"
                    placeholder="验证码"
                    prefix-icon="el-icon-picture"
                    size="medium"
                  />
                </el-col>
                <el-col
                  :span="10"
                  class="captcha-image"
                >
                  <img
                    :src="captchaUrl"
                    alt="验证码"
                    @click="refreshCaptcha"
                  >
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.rememberMe">
                记住我
              </el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="login-btn"
                :loading="loading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCaptchaUrl, validateCaptcha, setToken } from '@/utils/auth'
import $ from 'jquery'

export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: 'admin123',
        password: '123456',
        captcha: '',
        rememberMe: false
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      captchaUrl: '',
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created () {
    this.refreshCaptcha()
    this.loadRememberedAccount()
  },
  methods: {
    // 刷新验证码（前端生成）
    refreshCaptcha () {
      this.captchaUrl = getCaptchaUrl()
    },

    // 加载记住的账号
    loadRememberedAccount () {
      if (localStorage.getItem('rememberMe') === 'true') {
        this.loginForm.username = localStorage.getItem('username') || 'admin'
        this.loginForm.password = localStorage.getItem('password') || '123456'
        this.loginForm.rememberMe = true
      }
    },

    // 处理登录（使用jQuery Ajax）
    handleLogin () {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return

        // 前端验证码校验
        if (!validateCaptcha(this.loginForm.captcha)) {
          this.$message.error('验证码错误')
          this.refreshCaptcha()
          this.loginForm.captcha = ''
          return
        }

        this.loading = true

        // 使用jQuery Ajax发送请求
        $.ajax({
          url: 'http://localhost:3000/api/login',
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            username: this.loginForm.username.trim(),
            passwordHash: this.loginForm.password
          }),
          success: (response) => {
            console.log(response)
            if (response.code === 200) {
              // 1. 显示登录成功提示
              this.$message.success('登录成功')

              // // 保存token
              setToken(response.data.token)

              // 安全构造用户数据对象
              const userData = {
                name: response.data.realName || response.data.username, // 完全信任后端
                avatar: response.data.avatarUrl, // 不提供前端默认值
                ...(response.data.userInfo || {}), // 防止userInfo为undefined
                token: response.data.token // 确保包含token
              }

              // 统一更新用户信息
              this.$store.dispatch('user/setUserInfo', userData)

              // 记住我功能
              if (this.loginForm.rememberMe) {
                localStorage.setItem('username', this.loginForm.username)
                localStorage.setItem('password', this.loginForm.password)
                localStorage.setItem('rememberMe', true)
              } else {
                localStorage.removeItem('username')
                localStorage.removeItem('password')
                localStorage.removeItem('rememberMe')
              }

              // 跳转到首页或指定页面
              this.$router.push('/dashboard')
            } else {
              this.$message.error(response.message || '登录失败')
              this.refreshCaptcha()
            }
          },
          error: (xhr, status, error) => {
            if (xhr.status === 0) {
              this.$message.error('网络连接失败')
            } else if (xhr.responseJSON) {
              this.$message.error(xhr.responseJSON.message || '登录失败')
            } else {
              this.$message.error('请求失败: ' + xhr.status)
            }
            this.refreshCaptcha()
          },
          complete: () => {
            this.loading = false
          }
        })
      })
    }
  }
}

// export default {
//   name: 'Login',
//   data () {
//     return {
//       loginForm: {
//         username: 'admin',
//         password: '123456',
//         captcha: '',
//         uuid: '',
//         rememberMe: false
//       },
//       loginRules: {
//         username: [
//           { required: true, message: '请输入用户名', trigger: 'blur' }
//         ],
//         password: [
//           { required: true, message: '请输入密码', trigger: 'blur' },
//           { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
//         ],
//         captcha: [
//           { required: true, message: '请输入验证码', trigger: 'blur' }
//         ]
//       },
//       captchaUrl: '',
//       loading: false,
//       redirect: undefined
//     }
//   },
//   watch: {
//     $route: {
//       handler: function (route) {
//         this.redirect = route.query && route.query.redirect
//       },
//       immediate: true
//     }
//   },
//   created () {
//     this.refreshCaptcha()
//     // 记住我功能
//     if (localStorage.getItem('rememberMe') === 'true') {
//       this.loginForm.username = localStorage.getItem('username') || ''
//       this.loginForm.password = localStorage.getItem('password') || ''
//       this.loginForm.rememberMe = true
//     }
//   },
//   methods: {

//     refreshCaptcha () {
//       // 开发环境下使用前端生成的验证码
//       this.captchaUrl = getCaptchaUrl() // 直接调用前端生成函数
//       this.loginForm.uuid = 'dev-' + Date.now() // 生成模拟UUID

//       // 控制台输出验证码信息（方便测试）
//       console.groupCollapsed('[DEV] 验证码信息')
//       console.log('验证码URL:', this.captchaUrl)
//       console.groupEnd()
//     },

//     handleLogin () {
//       this.$refs.loginForm.validate(valid => {
//         if (!valid) return

//         // 新增验证码校验
//         if (!validateCaptcha(this.loginForm.captcha)) {
//           this.$message.error('验证码错误')
//           this.refreshCaptcha()
//           this.loginForm.captcha = ''
//           return
//         }

//         this.loading = true

//         // ======================[修改开始]======================
//         // 开发环境模拟登录（使用标准action替代直接commit）
//         if (process.env.NODE_ENV === 'development') {
//           console.log('[开发模式] 模拟登录流程')
//           this.$store.dispatch('user/login', {
//             username: this.loginForm.username,
//             password: 'dev-bypass'
//           }).then(() => {
//             // 确保开发环境使用有效头像路径
//             this.$store.commit('user/SET_AVATAR', require('@/assets/img/z.jpg'))
//             const redirect = this.redirect || '/dashboard'
//             this.$router.push(redirect)
//           }).finally(() => {
//             this.loading = false
//           })
//           return
//         }

//         // 记住我功能
//         if (this.loginForm.rememberMe) {
//           localStorage.setItem('username', this.loginForm.username)
//           localStorage.setItem('password', this.loginForm.password)
//           localStorage.setItem('rememberMe', this.loginForm.rememberMe)
//         } else {
//           localStorage.removeItem('username')
//           localStorage.removeItem('password')
//           localStorage.removeItem('rememberMe')
//         }

//         // 正式环境登录
//         this.$store.dispatch('user/Login', this.loginForm)
//           .then(() => {
//             this.$router.push({ path: this.redirect || '/' })
//           })
//           .catch(() => {
//             this.refreshCaptcha()
//           })
//           .finally(() => {
//             this.loading = false
//           })
//       })
//     }
//   }
// }
</script>

<style lang="scss" scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('/src/assets/img/19.jpg') no-repeat center center;
  background-size: cover;
  overflow: hidden;

  .login-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }

  .login-content {
    width: 100%;
    max-width: 500px;
    padding: 0 20px;
    text-align: center;
  }

  .system-title {
    color: #fff;
    font-size: 32px;
    margin-bottom: 40px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
    font-weight: 500;
  }

  .login-box {
    background-color: #fff;
    border-radius: 8px;
    padding: 40px 35px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);

    .login-heading {
      font-size: 22px;
      color: #333;
      margin-bottom: 30px;
      font-weight: 500;
    }

    .captcha-image {
      height: 40px;
      border-radius: 4px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      img {
        width: 100%;
        height: 100%;
        cursor: pointer;
        display: block;
      }
    }

    .login-btn {
      width: 100%;
      height: 44px;
      font-size: 16px;
      margin-top: 10px;
    }

    .el-checkbox {
      color: #666;
    }
  }
}
</style>
